<?php
/**
 * Youdian Content Management System
 * Copyright (C) YoudianSoft Co.,Ltd (http://www.youdiancms.com). All rights reserved.
 */
class PluginAction extends AdminBaseAction {
	private $_pluginMenuGroupID = 31; //我的插件所属的分组菜单ID
	/**
	 * 获取插件列表
	 */
	private function _getPlugList(){
		$PluginUrl = "http://www.youdiancms.com/";
		$IsOem = C('CMSEnName')=='YouDianCMS' ? false : true;
		$list[122] = array( //数据采集
			'PluginDescription'=>'用于采集网站文章，可针对不同的字段设置不同的采集规则。支持图片自动上传、内容分页采集、自动生成缩略图',
			'PluginPrice'=>'免费',
			'PluginAuthor'=>'官方',
			'PluginVersion'=>'1.0.0',
			'PluginPicture'=>'plugin_caiji.png',
			'PluginUrl'=>$PluginUrl.'plugin/caiji.html',
		);
		$list[148] = array( //三级分销
				'PluginDescription'=>'三级裂变式分销、自定义佣金比例、快速发展分销商，实现快速推广与销售产品',
				'PluginPrice'=>'免费',
				'PluginAuthor'=>'官方',
				'PluginVersion'=>'1.0.0',
				'PluginPicture'=>'plugin_fenxiao.png',
				'PluginUrl'=>$PluginUrl.'plugin/fenxiao.html',
		);
		$list[149] = array( //七牛云存储
				'PluginDescription'=>'通过七牛云存储给网站图片、css、js等静态资源加速，极大提升网站加载速度，让网站秒开！',
				'PluginPrice'=>'免费',
				'PluginAuthor'=>'官方',
				'PluginVersion'=>'1.0.0',
				'PluginPicture'=>'plugin_qiniu.png',
				'PluginUrl'=>$PluginUrl.'plugin/qiniu.html',
		);
		$list[151] = array( //邮件群发
				'PluginDescription'=>'可以一键给所有会员或指定组的会员群发邮件，支持群发自定义邮箱，支持邮箱号码导入导出',
				'PluginPrice'=>'免费',
				'PluginAuthor'=>'官方',
				'PluginVersion'=>'1.0.0',
				'PluginPicture'=>'plugin_email.png',
				'PluginUrl'=>$PluginUrl.'plugin/email.html',
		);
		$list[152] = array( //图像批量处理
				'PluginDescription'=>'可以批量处理（改变尺寸、加水印、瘦身、格式转换等）网站图片',
				'PluginPrice'=>'免费',
				'PluginAuthor'=>'官方',
				'PluginVersion'=>'1.0.0',
				'PluginPicture'=>'plugin_imageprocess.png',
				'PluginUrl'=>$PluginUrl.'plugin/imageprocess.html',
		);
		
		$m = D('Admin/Menu');
		$data = $m->getMenu($this->_pluginMenuGroupID,  -1);
		$result = array();
		if(!empty($data)){
			$n = count($data);
			for ($i=0; $i<$n; $i++){
				$PluginID = $data[$i]['MenuID'];
				$result[$i]['PluginID'] = $PluginID;
				$result[$i]['PluginName'] = $data[$i]['MenuName'];
				$result[$i]['PluginOrder'] = $data[$i]['MenuOrder'];
				$result[$i]['IsEnable'] = $data[$i]['IsEnable'];
				if( isset($list[$PluginID]) ){
					$result[$i]['PluginDescription'] = $list[$PluginID]['PluginDescription'];
					$result[$i]['PluginPrice'] = $list[$PluginID]['PluginPrice'];
					$result[$i]['PluginAuthor'] = $list[$PluginID]['PluginAuthor'];
					$result[$i]['PluginVersion'] = $list[$PluginID]['PluginVersion'];
					$result[$i]['PluginPicture'] = $list[$PluginID]['PluginPicture'];
					//如果是OEM贴牌用户，则不显示插件介绍链接
					$result[$i]['PluginUrl'] = $IsOem ? '' : $list[$PluginID]['PluginUrl'];
				}
			}
		}
		return $result;
	}
	
	/**
	 * 插件列表
	 */
	function index(){
		header("Content-Type:text/html; charset=utf-8");
		$data = $this->_getPlugList();
		$this->assign("Data", $data);
		$this->display();
	}
	
	/**
	 * 插件排序
	 */
	function sort(){
		header("Content-Type:text/html; charset=utf-8");
		$m = D('Admin/Menu');
		$id = $_POST['PluginOrderID'];
		$order = $_POST['PluginOrder'];

		$n = count($id);
		for($i = 0; $i < $n; $i++){
			$where['MenuID'] = intval( $id[$i] );
			$where['MenuGroupID'] = $this->_pluginMenuGroupID;
			$m->where($where)->setField('MenuOrder', $order[$i]);
		}
		$this->ajaxReturn(null, '' , 1);
		//redirect(__URL__."/index");
	}
	
	/**
	 * 是否启用插件
	 */
	function enable(){
		header("Content-Type:text/html; charset=utf-8");
		$PluginID = intval($_POST['PluginID']);
		$IsEnable = intval($_POST['IsEnable']);
		$m = D('Admin/Menu');
		$where['MenuID'] = $PluginID;
		$where['MenuGroupID'] = $this->_pluginMenuGroupID;
		$result = $m->where($where)->setField('IsEnable', $IsEnable);
		
		//禁止三级分销插件的同时，需要关闭分销功能
		if($IsEnable==0 && $PluginID==148){
			$mc = D('Admin/Config');
			$mc->where("ConfigName='DistributeEnable'")->setField('ConfigValue',0);
		}
		
		//禁止七牛云插件的同时，需要禁用七牛云功能
		if($IsEnable==0 && $PluginID==149){
			$mc = D('Admin/Config');
			$mc->where("ConfigName='QiniuEnable'")->setField('ConfigValue',0);
		}
		
		if($result){
			$this->ajaxReturn(null, '' , 1);
		}else{
			$this->ajaxReturn(null, '' , 0);
		}
	}
	
	/**
	 * 三级分销首页
	 */
	function distribution(){
		header("Content-Type:text/html; charset=utf-8");
		
		$this->display();
	}
	
	/**
	 * 三级分销设置
	 */
	function distributionConfig(){
		header("Content-Type:text/html; charset=utf-8");
		$m = D('Admin/Config');
		$data = $m->getConfig('other'); //配置数据不从缓存中提取
		
		//设置
		$DistributeEnable = empty($data['DistributeEnable']) ? 0 : $data['DistributeEnable'];
		$DistributeRequirement = empty($data['DistributeRequirement']) ? 1 : $data['DistributeRequirement'];
		$DistributeMode = empty($data['DistributeMode']) ? 1 : $data['DistributeMode'];
		$MinMoney = intval($data['MinMoney']);
		$OrderRate = doubleval($data['OrderRate']);
		$BuyerRate  = doubleval($data['BuyerRate']);
		//默认为三级分销
		$ReturnGrade = empty($data['ReturnGrade']) ? 3 : $data['ReturnGrade'];
		
		$this->assign('DistributeEnable', $DistributeEnable );
		$this->assign('DistributeRequirement', $DistributeRequirement);
		$this->assign('MinMoney', $MinMoney );
		$this->assign('DistributeMode', $DistributeMode );
		$this->assign('OrderRate', $OrderRate );
		$this->assign('BuyerRate', $BuyerRate );
		$this->assign('ReturnGrade', $ReturnGrade );
		
		//返利设置
		$this->assign('DistributeEmail', $data['DistributeEmail'] );
		$this->assign('DistributeEmailTitle', $data['DistributeEmailTitle']);
		$this->assign('DistributeEmailBody', $data['DistributeEmailBody'] );
		$this->assign('DistributeSms', $data['DistributeSms']);
		$this->assign('DistributeSmsBody', $data['DistributeSmsBody'] );

		$this->assign('Action', __URL__.'/saveDistributionConfig' );
		$this->display();
	}
	
	/**
	 * 保存三级分销设置
	 */
	function saveDistributionConfig(){
		if( isset($_POST) ){  //保存配置到数据库
			unset( $_POST['__hash__'] );
			$m = D("Admin/Config");
			if( $m->saveConfig($_POST) ){
				WriteLog();
				$this->ajaxReturn(null, '保存成功!' , 1);
			}else{
				$this->ajaxReturn(null, '保存失败!' , 0);
			}
		}
	}
	
	/**
	 * 分销商品列表
	 */
	function distributionGoods(){
		header("Content-Type:text/html; charset=utf-8");
		$p['ModuleName'] = 'Info'; //表示有分页
		$p['GetFunctionName'] = 'getDistributionGoods';
		$p['GetCountFunctionName'] = 'getDistributionGoodsCount'; 
		
		$p['HasPage'] = true; //表示有分页
		$Keywords = !empty($_REQUEST['Keywords']) ? $_REQUEST['Keywords'] : '';
		$ChannelID = !empty($_REQUEST['ChannelID']) ? intval($_REQUEST['ChannelID']) : -1;
		$p['Parameter'] = array(
				'Keywords' => $Keywords,
				'ChannelID' => $ChannelID,
		);
		
		$m = D('Admin/Channel');
		$AdminGroupID = session('AdminGroupID');
		$MenuOwner = (strtolower(GROUP_NAME)=='admin') ? 1 : 0;
		$Channel = $m->getChannelPurview($MenuOwner, $AdminGroupID);
		foreach ($Channel as $v){
			$hasChild = $v['HasChild'];
			$channelModelID = $v['ChannelModelID'];
			if( $channelModelID == 36 ){
				$ChannelNew[] = array('ChannelID' => $v['ChannelID'],'ChannelName' => $v['ChannelName']);
			}
		}
		unset( $Channel );
		$this->assign('Channel', $ChannelNew);
		
		$this->assign("DistributeMode", $GLOBALS['Config']['DistributeMode']);
		$this->opIndex( $p );
	}
	
	/**
	 * 分销商列表
	 */
	function distributor(){
		header("Content-Type:text/html; charset=utf-8");
		$p['ModuleName'] = 'Member'; //表示有分页
		$p['GetFunctionName'] = 'getDistributor';
		$p['GetCountFunctionName'] = 'getDistributorCount';
		$p['HasPage'] = true; //表示有分页
		$Keywords = !empty($_REQUEST['Keywords']) ? $_REQUEST['Keywords'] : '';
		$DistributorLevelID = !empty($_REQUEST['DistributorLevelID']) ? intval($_REQUEST['DistributorLevelID']) : -1;
		$p['Parameter'] = array(
				'Keywords' => $Keywords,
				'DistributorLevelID' => $DistributorLevelID,
				'IsDistributor' => 1,
		);		
		$this->opIndex( $p );
	}
	
	/**
	 * 查找分销商
	 */
	function findDistributor(){
		header("Content-Type:text/html; charset=utf-8");
		$m = D("Admin/Member");
		$result = $m->findDistributor( $_REQUEST['MembeID'] );
		$this->ajaxReturn($result, '' , 1);
	}
	
	/**
	 * 设置分销商
	 */
	function setDistributor(){
		header("Content-Type:text/html; charset=utf-8");
		$MemberID =  intval($_POST['MemberID']);
		$IsDistributor = intval($_POST['IsDistributor']);
		$DistributorLevelID = intval($_POST['DistributorLevelID']);
		$m = D("Admin/Member");
		$where['MemberID'] = $MemberID;
		$data['IsDistributor'] = $IsDistributor;
		if($IsDistributor == 1){
			$data['DistributorLevelID'] = $DistributorLevelID;
		}
		$result = $m->where($where)->setField($data);
		if( $result === false){
			$this->ajaxReturn(null, '设置失败!' , 0);
		}else{
			$this->ajaxReturn(null, '设置成功!' , 1);
		}
	}
	
	/**
	 * 添加分销商
	 */
	function addDistributor(){
		header("Content-Type:text/html; charset=utf-8");
		$Keywords = isset($_REQUEST['Keywords']) ? $_REQUEST['Keywords'] : '';
		$p['IsDistributor'] = 0;
		$m = D('Admin/Member');
		import("ORG.Util.Page");
		$TotalPage = $m->getCount($Keywords, 1, -1, $p);
		$PageSize = 15;
		
		$Page = new Page($TotalPage, $PageSize);
		if( $Keywords != ''){
			$Page->parameter .= "&Keywords=$Keywords";
		}
		$Page->rollPage = $this->AdminRollPage;
		$ShowPage = $Page->show();
		$Member= $m->getMember($Page->firstRow, $Page->listRows, $Keywords, 1, -1, $p);
		
		$this->assign("AdminPageSize", $PageSize);
		$this->assign('NowPage', $Page->getNowPage());
		$this->assign('Keywords', $Keywords);
		$this->assign('Data', $Member);
		$this->assign('Page', $ShowPage); //分页条
		$this->display();
	}
	
	//保存设置分销商
	function saveAddDistributor(){
		header("Content-Type:text/html; charset=utf-8");
		$m = D('Admin/Member');
		$result = $m->setDistributorLevel($_POST['id'], $_POST['DistributorLevelID']);
		if( $result === false){
			$this->ajaxReturn(null, '设置失败!' , 0);
		}else{
			$this->ajaxReturn(null, '设置成功!' , 1);
		}
	}
	
	/**
	 * 分销关系
	 */
	function distributionRelation(){
		header("Content-Type:text/html; charset=utf-8");
		$m = D('Admin/Member');
		if(!empty($_REQUEST['Keywords'])){
			$p['Keywords'] = trim($_REQUEST['Keywords']);
		}else{
			$p['Keywords'] = '';
			$p['InviterID']=0; //仅获取顶级分销商
		}
		$p['IsDistributor']=1;
		$data = $m->getDistributor(-1, -1, $p);
		$this->assign('Keywords', $p['Keywords'] );
		$this->assign('Data', $data);
		$this->display();
	}
	
	/**
	 * 获取下级分销商
	 */
	function getNextDistributionRelation(){
		header("Content-Type:text/html; charset=utf-8");
		$MemberID = intval($_REQUEST['MemberID']);
		$m = D('Admin/Member');
		$data = $m->getNextDistributionRelation($MemberID);
		$this->ajaxReturn($data, '', 1);
	}
	
	/**
	 * 分销商等级
	 */
	function distributorLevel(){
		header("Content-Type:text/html; charset=utf-8");
		$p['ModuleName'] = 'DistributorLevel'; //表示有分页
		$this->opIndex( $p );
	}
	
	/**
	 * 删除分销商级别
	 */
	function delDistributorLevel(){
		header("Content-Type:text/html; charset=utf-8");
		$id = intval($_REQUEST['id'] );
		$mm = D('Admin/Member');
		$MemberID = $mm->where("DistributorLevelID={$id}")->getField('MemberID');
		if($MemberID > 0){
			$this->ajaxReturn(null, '此等级存在数据，不能删除', 0);
		}
		
		$m = D('Admin/DistributorLevel');
		$result = $m->delDistributorLevel( $id );
		if($result){
			$this->ajaxReturn(null, '', 1);
		}else{
			$this->ajaxReturn(null, '', 0);
		}
	}
	
	/**
	 * 添加分销商级别
	 */
	function addDistributorLevel(){
		header("Content-Type:text/html; charset=utf-8");
		unset( $_POST['DistributorLevelID'] );
		if( empty($_POST['DistributorLevelName']) ){
			$this->ajaxReturn('DistributorLevelName', '等级名称不能为空', 0);
		}
		$m = D('Admin/DistributorLevel');
		if( $m->create() ){
			$result = $m->add();
			if($result){
				$LogDescription = 'ID:'.$m->getLastInsID();
				WriteLog( $LogDescription );
				$this->ajaxReturn(null, '添加成功', 1);
			}else{
				$this->ajaxReturn(null, '添加失败', 0);
			}
		}
	}
	
	/**
	 * 修改分销商等级
	 */
	function modifyDistributorLevel(){
		header("Content-Type:text/html; charset=utf-8");
		if( empty($_POST['DistributorLevelName']) ){
			$this->ajaxReturn('DistributorLevelName', '等级名称不能为空', 0);
		}
		$m = D('Admin/DistributorLevel');
		if( $m->create() ){
			$result = $m->save();
			if($result===false){
				$this->ajaxReturn(null, '修改失败', 0);
			}else{
				$LogDescription = 'ID:'.$_POST['DistributorLevelID'];
				WriteLog( $LogDescription );
				$this->ajaxReturn(null, '修改成功', 1);
			}
		}else{
			$this->ajaxReturn(null, $m->getError() , 0);
		}
	}
	
	/**
	 * 七牛云存储设置
	 */
	function qiniuConfig(){
		header("Content-Type:text/html; charset=utf-8");
		$m = D('Admin/Config');
		$data = $m->getConfig('other'); //配置数据不从缓存中提取
	
		//搜索引擎优化设置
		$QiniuEnable = empty($data['QiniuEnable']) ? 0 : $data['QiniuEnable'];
		$this->assign('QiniuEnable', $QiniuEnable );
		$this->assign('QiniuAccessKey', $data['QiniuAccessKey']);
		$this->assign('QiniuSecretKey', $data['QiniuSecretKey'] );
		$this->assign('QiniuBucketName', $data['QiniuBucketName'] );
		$this->assign('QiniuUrl', $data['QiniuUrl'] );
		$this->assign('QiniuMirrorUrl', $data['QiniuMirrorUrl'] );
		$this->assign('QiniuInterlaceEnable', $data['QiniuInterlaceEnable'] );
		$this->assign('QiniuFileType', $data['QiniuFileType'] );
		$this->assign('Action', __URL__.'/saveQiniuConfig' );
		$this->display();
	}
	
	function qiniuFile(){
		header("Content-Type:text/html; charset=utf-8");
		$QiniuEnable = $GLOBALS['Config']['QiniuEnable'];
		$data = array();
		$PageSize = 1000;
		if($QiniuEnable==1){
			import("@.Common.YdQiniu");
			$config['secretKey'] = $GLOBALS['Config']['QiniuSecretKey'];
			$config['accessKey'] = $GLOBALS['Config']['QiniuAccessKey'];
			$config['domain'] = $GLOBALS['Config']['QiniuUrl'];
			$config['bucket'] = $GLOBALS['Config']['QiniuBucketName'];
			$niu = new YdQiniu($config);
			$query = array();
			if( !empty($_REQUEST['Prefix']) ){
				$query['prefix'] = $_REQUEST['Prefix'];
			}
			if( !empty($_REQUEST['Marker']) ){
				$query['marker'] = $_REQUEST['Marker'];
			}
			$query['limit'] = $PageSize;
			$result = $niu->getList($query);
			if(!empty($result['items'])){
				$data = &$result['items'];
				$n = count($data);
				$domain = $GLOBALS['Config']['QiniuUrl'];
				for ($i=0; $i<$n; $i++){
					$data[$i]['fsize'] = byte_format( $data[$i]['fsize'] );
					$ext = strtolower(yd_file_ext($data[$i]['key']));
					$data[$i]['filetype'] = getTplFileType( ".{$ext}");
					//上传时间，单位：100纳秒，其值去掉低七位即为Unix时间戳。
					$ts = intval($data[$i]['putTime']/10000000);
					$data[$i]['putTime'] = yd_friend_date($ts);
					$extFile = './Public/Images/FileICO/'.$ext.'.gif';
					if( is_file( $extFile ) ){
						$data[$i]['ico'] = $this->WebPublic.'Images/FileICO/'.$ext.'.gif';
					}else{
						$data[$i]['ico'] = $this->WebPublic.'Images/FileICO/unknown.gif';
					}
					$data[$i]['fileurl'] = $domain.'/'.ltrim($data[$i]['key'],'/');
				}
			}
		}
		$this->assign('PageSize', $PageSize);
		$this->assign('Prefix', $_REQUEST['Prefix'] );
		$this->assign('NextMarker', $result['marker']);
		$this->assign('Data', $result['items'] );
		$this->display();
	}
	
	/**
	 * 保存七牛云存储
	 */
	function saveQiniuConfig(){
		if( isset($_POST) ){  //保存配置到数据库
			unset( $_POST['__hash__'] );
			if($_POST['QiniuEnable']==1){
				//AccessKey
				$_POST['QiniuAccessKey'] = trim($_POST['QiniuAccessKey']);
				if(empty($_POST['QiniuAccessKey'])){
					$this->ajaxReturn(null, 'AccessKey不能为空' , 0);
				}
				//SecretKey
				$_POST['QiniuSecretKey'] = trim($_POST['QiniuSecretKey']);
				if(empty($_POST['QiniuSecretKey'])){
					$this->ajaxReturn(null, 'SecretKey不能为空' , 0);
				}
				//存储空间名
				$_POST['QiniuBucketName'] = trim($_POST['QiniuBucketName']);
				if(empty($_POST['QiniuBucketName'])){
					$this->ajaxReturn(null, '存储空间名不能为空' , 0);
				}
				//镜像源
				$_POST['QiniuMirrorUrl'] = strtolower(trim($_POST['QiniuMirrorUrl']));
				$_POST['QiniuMirrorUrl'] = trim($_POST['QiniuMirrorUrl'],'/');
				if(empty($_POST['QiniuMirrorUrl'])){
					$this->ajaxReturn(null, '镜像源不能为空' , 0);
				}
				if('http' != substr($_POST['QiniuMirrorUrl'], 0, 4)){
					$this->ajaxReturn(null, '镜像源域名必须以http开头' , 0);
				}
				
				//访问域名结尾不能为/
				$_POST['QiniuUrl'] = strtolower(trim($_POST['QiniuUrl']));
				$_POST['QiniuUrl'] = trim($_POST['QiniuUrl'],'/');
				if(empty($_POST['QiniuUrl'])){
					$this->ajaxReturn(null, '访问域名不能为空' , 0);
				}
				if('http' != substr($_POST['QiniuUrl'], 0, 4)){
					$this->ajaxReturn(null, '访问域名必须以http开头' , 0);
				}
				//扩展名有效性检查
				$QiniuFileType = str_replace(' ', '', trim($_POST['QiniuFileType']));
				$QiniuFileType = trim($QiniuFileType, '|');
				if(empty($_POST['QiniuFileType'])){
					$this->ajaxReturn(null, '扩展名不能为空' , 0);
				}
				if(!preg_match('/^[a-zA-Z0-9|]+$/', $QiniuFileType) ){
					$this->ajaxReturn(null, '扩展名格式包含无效字符' , 0);
				}
				$_POST['QiniuFileType'] = $QiniuFileType;
				//连接七牛云，设置镜像源地址
				import("@.Common.YdQiniu");
				$config['secretKey'] = $_POST['QiniuSecretKey'];
				$config['accessKey'] = $_POST['QiniuAccessKey'];
				$config['domain'] = $_POST['QiniuUrl'];
				$config['bucket'] = $_POST['QiniuBucketName'];
				$niu = new YdQiniu($config);
				$response = $niu->setMirrorUrl($_POST['QiniuMirrorUrl']);
				if( !empty($niu->error) ){
					$this->ajaxReturn(null, '设置镜像域名失败' , 0);
				}
			}
			
			$m = D("Admin/Config");
			if( $m->saveConfig($_POST) ){
				WriteLog();
				$this->ajaxReturn(null, '保存成功!' , 1);
			}else{
				$this->ajaxReturn(null, '保存失败!' , 0);
			}
		}
	}
	
	/**
	 * 获取七牛储存空间对应的域名
	 */
	function getBucketDomain(){
		header("Content-Type:text/html; charset=utf-8");
		import("@.Common.YdQiniu");
		$config['secretKey'] = $_POST['sk'];
		$config['accessKey'] = $_POST['ak'];
		$config['bucket'] = $_POST['bucket'];
		$niu = new YdQiniu($config);
		$res = $niu->getBucketDomain();
		if( !empty($res) ){
			$domain = implode('&nbsp;&nbsp;&nbsp;&nbsp;', $res);
			$msg = "当前储存空间域名：{$domain}";
			//获取推荐域名，一般赠送的域名是4级域名，如：ozrvg3g67.bkt.clouddn.com
			$suggest = $res[0];
			foreach ($res as $v){
				$n = substr_count($v,'.');
				if($n<=2){
					$suggest = $v;
					break;
				}
			}
			$suggest = get_current_protocal().$suggest;
			$this->ajaxReturn($suggest, $msg , 1);
		}else{
			$this->ajaxReturn(null, '获取域名失败，请检查AccessKey、SecretKey、存储空间名是否正确！' , 0);
		}
	}
	
	/**
	 * 七牛文件重命名
	 */
	function qiniuRename(){
			$OldFileName = trim($_POST['OldFileName']);
			$NewFileName = trim($_POST['NewFileName']);
			if(empty($NewFileName)){
				$this->ajaxReturn(null, '文件名不能为空' , 0);
			}
			if($OldFileName==$NewFileName){
				$this->ajaxReturn(null, '新文件名和旧文件名不能相同' , 0);
			}

			//连接七牛云，设置镜像源地址
			import("@.Common.YdQiniu");
			$config['secretKey'] = $GLOBALS['Config']['QiniuSecretKey'];
			$config['accessKey'] = $GLOBALS['Config']['QiniuAccessKey'];
			$config['domain'] = $GLOBALS['Config']['QiniuUrl'];
			$config['bucket'] = $GLOBALS['Config']['QiniuBucketName'];
			$niu = new YdQiniu($config);
			$result= $niu->rename($OldFileName, $NewFileName);
			if( !empty($niu->error) ){
				$this->ajaxReturn(null, '重命名失败！{$niu->error}' , 0);
			}else{
				$data['NewFileName'] = $NewFileName;
				$data['FileUrl'] = $config['domain'].'/'.ltrim($NewFileName,'/');
				$this->ajaxReturn($data, '重命名成功！' , 1);
			}
	}
	
	/**
	 * 七牛删除文件
	 */
	function qiniuDelFile(){
		if(empty($_POST['Key']) || !is_array($_POST['Key'])){
			$this->ajaxReturn(null, '请选择文件！' , 0);
		}
		import("@.Common.YdQiniu");
		$config['secretKey'] = $GLOBALS['Config']['QiniuSecretKey'];
		$config['accessKey'] = $GLOBALS['Config']['QiniuAccessKey'];
		$config['domain'] = $GLOBALS['Config']['QiniuUrl'];
		$config['bucket'] = $GLOBALS['Config']['QiniuBucketName'];
		$niu = new YdQiniu($config);
		$result= $niu->delBatch($_POST['Key']);
		if( !empty($niu->error) ){
			$this->ajaxReturn(null, '删除失败！{$niu->error}' , 0);
		}else{
			$this->ajaxReturn(null, '删除成功！' , 1);
		}
	}
	
	/**
	 * 七牛文件上传
	 */
	function qiniuUpload(){
		header("Content-Type:text/html; charset=utf-8");
		$QiniuEnable = $GLOBALS['Config']['QiniuEnable'];
		$UploadToken = 0;
		if($QiniuEnable==1){
			import("@.Common.YdQiniu");
			$config['secretKey'] = $GLOBALS['Config']['QiniuSecretKey'];
			$config['accessKey'] = $GLOBALS['Config']['QiniuAccessKey'];
			$config['domain'] = $GLOBALS['Config']['QiniuUrl'];
			$config['bucket'] = $GLOBALS['Config']['QiniuBucketName'];
			$niu = new YdQiniu($config);
			$UploadToken = $niu->UploadToken($config['secretKey'], $config['accessKey']);
		}
		$MaxUploadSize = "1024"; //最大上传大小
		$this->assign('MaxUploadSize', $MaxUploadSize);
		$this->assign('UploadToken', $UploadToken);
		$this->assign('QiniuEnable', $QiniuEnable);
		$this->assign('Domain', $config['domain'] );
		$this->display();
	}
	
	/**
	 * 图像批量处理
	 */
	function imageProcess(){
		header("Content-Type:text/html; charset=utf-8");
		$data = $this->getImageProcessConfig();
		$MyFont = GetWaterFonts();
		$this->assign('MyFont',$MyFont);
		$this->assign($data);
		$this->assign('Action', __URL__.'/saveImageProcess' );
		$this->display();
	}
	
	//水印预览
	function waterPreview(){
		return;
		header("Content-type: image/jpg");
		$src = './Public/Images/standard/1.jpg';
		$dst = RUNTIME_PATH.'waterpreview.jpg';
		if( is_file($dst) ){
			@unlink($dst);
		}
		import('ORG.Util.Image.ThinkImage');
		$img = new ThinkImage(THINKIMAGE_GD, $src);
		$type = intval($_GET['WaterType']);
		$position = $_GET['WaterPosition'];
		if( $type == 1 ){ //图片水印
			//初始化时，判断水印图片是否存在
			$pic = $_SERVER['DOCUMENT_ROOT'].$_GET['WaterPic'];
			$img->water($pic, $position)->save($dst);
		}else if( $type == 2 ){ //文字水印
			$text = $_GET['WaterText'];
			$font = "";
			if( !empty($_GET['WaterFont']) ){
				$font = './Public/font/'.$_GET['WaterFont'];
				if(!file_exists($font)){
					$font = '';
				}
			}
			$size = $_GET['WaterTextSize'];
			$color= $_GET['WaterTextColor'];
			$angle = $_GET['WaterTextAngle'];
			$offset = array($_GET['WaterOffsetX'], $_GET['WaterOffsetY']);
			$img->text($text, $font, $size, $color, $position, $offset, $angle)->save($dst);
		}
		if( file_exists($dst) ){
			$g = imagecreatefromjpeg($dst);
			imagejpeg($g, NULL, 100);
			imagedestroy($g);
		}
	}
	
	/**
	 * 获取图像处理配置参数
	 */
	private function getImageProcessConfig(){
		$m = D('Admin/Config');
		$data = $m->where("ConfigName='ImageProcess'")->getField('ConfigValue');
		$data = !empty($data) ? json_decode($data, true) : array();
		foreach ($data as $k=>$v){
			if($v == ''){
				unset($data[$k]);
			}
		}
		$data['WaterText'] = urldecode($data['WaterText']);
		$default = array(
				'ThumbType'=>2,
				'ThumbWidth'=>'200',
				'ThumbHeight'=>'200',
		
				'WaterType'=>2,
				'WaterFont'=>'arial.ttf',
				'WaterTextSize'=>12,
				'WaterTextColor'=>'#FF0000',
				'WaterTextAngle'=>0,
				'WaterOffsetX'=>0,
				'WaterOffsetY'=>0,
				'WaterPosition'=>9,
		
				'ImageFormat'=>'jpg',
				'JpegQuality'=>80,
				'SaveType'=>1,
		);
		$data = array_merge($default, $data);
		return $data;
	}
	
	/**
	 * 保存图像批量处理设置
	 */
	function saveImageProcess(){
		if( isset($_POST) ){
			$this->checkImageProcessParams();
			unset( $_POST['__hash__'] );
			$_POST['WaterText'] = urlencode($_POST['WaterText']); //先编码，否则会产生乱码
			$content = json_encode($_POST);
			$m = D("Admin/Config");
			$b = $m->where("ConfigName='ImageProcess'")->setField('ConfigValue',$content);
			if($b !== false){
				$this->ajaxReturn(null, '图像处理初始化成功!' , 1);
			}else{
				$this->ajaxReturn(null, '图像处理初始化失败!' , 0);
			}
		}
	}
	
	//检查图像处理参数
	private function checkImageProcessParams(){
		//调整大小
		if($_POST['Size'] == 1){
			if( !is_numeric($_POST['ThumbWidth'])){
				$this->ajaxReturn(null, '宽度必须为数字!' , 0);
			}
			if( !is_numeric($_POST['ThumbHeight'])){
				$this->ajaxReturn(null, '高度必须为数字!' , 0);
			}
		}
		
		//检查水印是否存在
		if($_POST['Water'] == 1){
			if( $_POST['WaterType'] == 1 ){ //图片水印
				$WaterPic = $_SERVER['DOCUMENT_ROOT'].$_POST['WaterPic'];
				if(!file_exists($WaterPic)){
					$this->ajaxReturn(null, "水印图片{$WaterPic}不存在!" , 0);
				}
			}else{ //文字水印
				if( !empty($_POST['WaterFont']) ){
					$WaterFont= './Public/font/'.$_POST['WaterFont'];
					if(!file_exists($WaterFont)){
						$this->ajaxReturn(null, "水印字体文件{$WaterFont}不存在!" , 0);
					}
				}
				$_POST['WaterTextSize'] = intval($_POST['WaterTextSize']);
				$_POST['WaterTextAngle'] = intval($_POST['WaterTextAngle']);
				$_POST['WaterOffsetX'] = intval($_POST['WaterOffsetX']);
				$_POST['WaterOffsetY'] = intval($_POST['WaterOffsetY']);
				$_POST['WaterPosition'] = intval($_POST['WaterPosition']);
			}
		}
		
		//格式转换
		if($_POST['Format'] == 1){
			if( !is_numeric($_POST['JpegQuality'])){
				$this->ajaxReturn(null, '图像品质必须为数字!' , 0);
			}
			if( $_POST['JpegQuality']<0 || $_POST['JpegQuality']>100 ){
				$this->ajaxReturn(null, '图像品质必须>=0或<=100!' , 0);
			}
		}
		
		//检查Upload是否有写入全新
		if(!yd_is_writable("./Upload/") ){
			$this->ajaxReturn(null, './Upload/目录没有写入权限!' , 0);
		}
		
		//创建输出目录
		if($_POST['SaveType'] == 2){
			$SavePath = './Upload/'.trim($_POST['SavePath'],'/');
			if(!file_exists($SavePath)){
				$b = mkdir($SavePath, 0755, true);
				if(!b){
					$this->ajaxReturn(null, "创建输出目录{$SavePath}失败!" , 0);
				}
			}
		}
	}
	
	/**
	 * 开始图像处理
	 */
	function startImageProcess(){
		header("Content-Type:text/html; charset=utf-8");
		//转化为绝对路径，若路径存在中文名称，则可能会报错
		$filename = $_SERVER['DOCUMENT_ROOT'].urldecode($_POST['FileName']);
		//需要判断，图像文件是否存在
		if(!file_exists($filename)){
			$errorFileName = basename($_POST['FileName']);
			$this->ajaxReturn(null, "图像 {$errorFileName} 不存在！" , 0);
		}
		//需要判断扩展名
		$ext = strtolower(yd_file_ext($filename));
		if( !in_array($ext, array('jpeg','jpg','gif','bmp','png'))){
			$this->ajaxReturn(null, "无法处理{$ext}格式的图像文件！" , 0);
		}
		import('ORG.Util.Image.ThinkImage');
		$config = $this->getImageProcessConfig();
		$SaveType = $config['SaveType'];
		if($SaveType == 1){ //覆盖
			$destFilename = $filename;
		}else{ //保存到指定目录
			$SavePath = './Upload/'.trim($config['SavePath'],'/');
			$destFilename = $SavePath.'/'.basename($filename);
		}
		$srcFilename = $filename;
		$HasProcessedWithOutput = false; //SavePath=2并且被处理过，便于在格式转换里删除中间结果
		try{
			//调整图像尺寸
			if($config['Size'] == 1){
				$img = new ThinkImage(THINKIMAGE_GD, $srcFilename);
				$width = $config['ThumbWidth'];
				$height = $config['ThumbHeight'];
				$type = $config['ThumbType'];
				$img->thumb($width, $height, $type)->save($destFilename);
				$srcFilename = $destFilename;
				if($SaveType==2)$HasProcessedWithOutput = true;
			}
			
			//添加水印
			if($config['Water'] == 1){
				$img = new ThinkImage(THINKIMAGE_GD, $srcFilename);
				$position = $config['WaterPosition'];
				if( $config['WaterType'] == 2 ){//文字水印
					$text = $config['WaterText'];
					$font = "";
					if( !empty($config['WaterFont']) ){
						$font = './Public/font/'.$config['WaterFont'];
						if(!file_exists($font)){
							$font = '';
						}
					}
					$size = $config['WaterTextSize'];
					$color= $config['WaterTextColor'];
					$angle = $config['WaterTextAngle'];
					$offset = array($config['WaterOffsetX'], $config['WaterOffsetY']);
					$img->text($text, $font, $size, $color, $position, $offset, $angle)->save($destFilename);
				}else if( $config['WaterType'] == 1 ){ //图片水印
					//初始化时，判断水印图片是否存在
					$pic = $_SERVER['DOCUMENT_ROOT'].$config['WaterPic'];
					$img->water($pic, $position)->save($destFilename);
				}
				$srcFilename = $destFilename;
				if($SaveType==2) $HasProcessedWithOutput = true;
			}
			
			//格式转换（放到最后）
			if($config['Format'] == 1){
				$toExt = $config['ImageFormat'];
				$fromExt = strtolower(yd_file_ext($srcFilename));
				$fromExt1 = $fromExt;
				if($fromExt=="jpeg" || $fromExt=="jpg") $fromExt1 = "jpg";
				//如果扩展名相同就无需转换，jpeg除外（因为可以设置单独的品质因数）
				if($toExt=="jpg" || $toExt != $fromExt1){
					$img = new ThinkImage(THINKIMAGE_GD, $srcFilename);
					$other['JpegQuality'] = $config['JpegQuality'];
					if($SaveType == 1){ //覆盖原文件
						$pos = strripos($srcFilename, '.');
						$destFilename = substr_replace($srcFilename, $toExt, $pos+1, 100);
						$img->saveAs($destFilename, $other);
						if($srcFilename!=$destFilename){
							unlink($srcFilename);
						}
					}else{ //输出到指定目录
						$pos = strripos($destFilename, '.');
						$destFilename = substr_replace($destFilename, $toExt, $pos+1, 100);
						$img->saveAs($destFilename, $other);
						//删除中间处理临时文件
						if($HasProcessedWithOutput && $srcFilename!=$destFilename){
							unlink($srcFilename);
						}
					}
				}else if($SaveType ==2 && !$HasProcessedWithOutput){ 
					//如果格式转换和目标文件相同，且之前没有处理过，则仅仅拷贝文件到目标目录
					copy($srcFilename,$destFilename);
				}
			}
		}catch(Exception $e){
			$error = $e->getMessage();
			$errorFileName = basename($_POST['FileName']);
			$msg = "处理图像{$errorFileName}失败，{$error}";
			$this->ajaxReturn(null, $msg, 0);
		}
		$this->ajaxReturn(null, '图像处理完成!' , 1);
	}
	
	/**
	 * 获取图像输出目录
	 */
	function getImageOutputDir(){
		header("Content-Type:text/html; charset=utf-8");
		//传入的参数都是没有路径前缀的
		$currentDir = trim($_GET['dir']);
		$prefix = "./Upload";
		$list = array();
		if(empty($currentDir)){
			$ParentDir = ''; //表示没有上一级目录
			$pattern = $prefix.'/*';
		}else{
			$dir = $prefix.'/'.trim($currentDir, '/').'/';
			$ParentDir = dirname($dir);
			$ParentDir =  ($ParentDir==$prefix) ? '' : substr($ParentDir, 9);
			$pattern = $dir.'*';
		}
		$data = glob($pattern, GLOB_ONLYDIR);
		$list = array();
		foreach ($data as $k=>$v){
			$FullDir = substr($v, 9);
			$DirName = basename($v);
			$list[] = array(
				'FullDir'=>$FullDir,
				'DirName'=>$DirName
			);
		}
		$this->ajaxReturn($list, $ParentDir, 1);
	}
}
